const Usecase = require('../../shared/usecase/Usecase')
const UserStatus = require('../../domain/user/UserStatus')
const {
  UserNotFoundError,
  UserHasRoleError,
} = require('../../domain/user/error')

class DeleteUser extends Usecase {
  constructor({ userRepo, database }) {
    super(['DeletedUser'])
    this.userRepo = userRepo
    this.sequelize = database.sequelize
  }

  async execute(data) {
    const { DeletedUser } = this.eventMap
    const user = await this.userRepo.findById(data, {
      include: ['roleList'],
    })
    if (!user) throw new UserNotFoundError(data)
    if (user.roleList.length) throw new UserHasRoleError(user.username)
    const transaction = await this.sequelize.transaction()
    try {
      user.status = UserStatus.ENABLE
      await this.userRepo.remove(user, { transaction })
      await transaction.commit()
      this.emit(DeletedUser, user)
    } catch (error) {
      await transaction.rollback()
      throw error
    }
  }
}

module.exports = DeleteUser
